package com.chenyu.util;

import java.io.File;
import java.util.*;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



public class Dom4JUtil {
    private static String filepath;

    /**
     *   获取根节点
     * @param fileName 文件名
     * @return  Element
     * @throws DocumentException
     */
    public static Element getRootElement(String fileName) throws DocumentException {
        filepath = Dom4JUtil.class.getClassLoader().getResource(fileName).getPath();
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        File file = new File(filepath);
        Document document = reader.read(file);
        return document.getRootElement();
    }

    /**
     * 获取根节点下的子节点（二级节点）
     * @return
     */
    public static List<Element> getElemts(String fileName) throws DocumentException {
        Element el = getRootElement(fileName);
        return el.elements();
    }

    /**
     * 获取指定的三级节点（key,val）
     * @return
     */
        public static Properties getThreeElemts(String fileName,String ElementName) throws DocumentException {
            final Properties map = new Properties();
            List<Element> list = getElemts(fileName);
            for(Element els : list){
                if(els.getName().equals(ElementName)){
                    List<Element> el = els.elements();
                    for(Element e : el){
                        map.put(e.getName(),e.getData().toString());
                    }

                }
            }
            return map;
    }
}
